package com.cnswhy.cloud.server.iot.controller;

import com.alibaba.fastjson.JSON;
import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.common.core.utils.SystemClockUtil;
import com.cnswhy.cloud.common.rabbitmq.service.MessageService;
import com.cnswhy.cloud.common.redis.service.RedisService;
import com.cnswhy.cloud.server.common.entity.constant.AmqpExchange;
import com.cnswhy.cloud.server.common.entity.enumeration.OrderPfxEnum;
import com.cnswhy.cloud.server.common.entity.mq.IotclOrderSplitMQ;
import com.cnswhy.cloud.server.core.entity.IotChargingLineInfo;
import com.cnswhy.cloud.server.core.entity.IotChargingLineScale;
import com.cnswhy.cloud.server.core.entity.IotChargingLineTransOrder;
import com.cnswhy.cloud.server.core.service.IotChargingLineInfoService;
import com.cnswhy.cloud.server.core.service.IotChargingLineScaleService;
import com.cnswhy.cloud.server.core.service.IotChargingLineTransOrderService;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.service.WxPayService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j

@Api(tags = "微信支付回调")
@RestController
@RequestMapping("/wxNotify")
public class WxNotifyController {

    @Autowired
    IotChargingLineTransOrderService iotChargingLineTransOrderService;
    @Autowired
    WxPayService wxPayService;
    @Autowired
    RedisService redisService;
    @Autowired
    IotChargingLineInfoService iotChargingLineInfoService;
    @Autowired
    IotChargingLineScaleService iotChargingLineScaleService;
    @Autowired
    MessageService messageService;

    /**
     * 微信支付回调
     */
    @ApiOperation(value = "微信支付回调", httpMethod = "GET")
    @RequestMapping(value = "/wxBack", method = {RequestMethod.POST,RequestMethod.GET})
    public String wxBack(HttpServletRequest request, HttpServletResponse response) {
        try {
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            WxPayOrderNotifyResult result = wxPayService.parseOrderNotifyResult(xmlResult);
            log.info(JSON.toJSONString(result));
            // 结果正确
            String orderId = result.getOutTradeNo();
            String tradeNo = result.getTransactionId();
            if(orderId.startsWith(OrderPfxEnum.IOTCL.getCode())){
                IotChargingLineTransOrder iotChargingLineTransOrder = iotChargingLineTransOrderService.getOne(Wraps.<IotChargingLineTransOrder>lbQ().eq(IotChargingLineTransOrder::getOrderId,orderId));
                //保存tradeNo
                iotChargingLineTransOrder.setStatus(2);
                iotChargingLineTransOrder.setWxOrderId(tradeNo);
                iotChargingLineTransOrder.setStartTime(SystemClockUtil.getLocalDateTime());
                iotChargingLineTransOrderService.updateById(iotChargingLineTransOrder);
                IotChargingLineInfo iotChargingLineInfo = iotChargingLineInfoService.getOne(Wraps.<IotChargingLineInfo>lbQ().eq(IotChargingLineInfo::getTerminalId,iotChargingLineTransOrder.getTerminalId()));
                iotChargingLineInfo.setStatus(1);
                iotChargingLineInfo.setStartTime(SystemClockUtil.getLocalDateTime());
                iotChargingLineInfo.setEndTime(SystemClockUtil.getLocalDateTime().plusHours(iotChargingLineTransOrder.getHours()));
                iotChargingLineInfoService.updateById(iotChargingLineInfo);

                // 分账
                messageService.sendQueueByObject(AmqpExchange.IOTCL_ORDER_SPLIT_MESSAGE, IotclOrderSplitMQ.builder().iotChargingLineOrderId(iotChargingLineTransOrder.getId()).build());

                IotChargingLineScale iotChargingLineScale = iotChargingLineScaleService.getById(iotChargingLineTransOrder.getMenuId());
                Long timeSeconds = 60* 60L * iotChargingLineScale.getHours();
                redisService.hset(OrderPfxEnum.IOTCL.getCode(), iotChargingLineInfo.getTerminalId(), iotChargingLineInfo, timeSeconds);
            }
            return WxPayNotifyResponse.success("处理成功!");
        } catch (Exception e) {
            log.error("微信回调结果异常,异常原因{}", e.getMessage());
            return WxPayNotifyResponse.fail(e.getMessage());
        }
    }
    /**
     * token
     */
    @ApiOperation(value = "token", httpMethod = "GET")
    @RequestMapping(value = "/token", method = {RequestMethod.POST,RequestMethod.GET})
    public String token(HttpServletRequest request, String signature,String timestamp,String nonce,String echostr) {
        try {
            log.info("request:signature {} timestamp {} nonce {} echostr {}",signature, timestamp,nonce, echostr);
            /*String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            log.info(xmlResult);*/
            return echostr;
        } catch (Exception e) {
            log.error("微信回调结果异常,异常原因{}", e.getMessage());
            return "success";
        }
    }



}
